package com.sgj.gulimall.ware.service.impl;

import com.sgj.common.enums.PurchaseDetailStatusEnum;
import com.sgj.common.enums.PurchaseStatusEnum;
import com.sgj.gulimall.ware.entity.PurchaseDetailEntity;
import com.sgj.gulimall.ware.service.PurchaseDetailService;
import com.sgj.gulimall.ware.service.WareSkuService;
import com.sgj.gulimall.ware.vo.MergeVo;
import com.sgj.gulimall.ware.vo.PurchaseDoneVo;
import com.sgj.gulimall.ware.vo.PurchaseDoneVo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sgj.common.utils.PageUtils;
import com.sgj.common.utils.Query;

import com.sgj.gulimall.ware.dao.PurchaseDao;
import com.sgj.gulimall.ware.entity.PurchaseEntity;
import com.sgj.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService detailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
                        .eq("status", PurchaseStatusEnum.CREATED.getCode())
                        .or().eq("status", PurchaseStatusEnum.ASSIGNED.getCode())
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (Objects.isNull(purchaseId)) {
            PurchaseEntity purchaseEntity = PurchaseEntity.builder()
                    .status(PurchaseStatusEnum.CREATED.getCode())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build();
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        // TODO 确认采购单状态是0，1才可以合并

        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> detailEntities = items.stream().map(item -> {
            return PurchaseDetailEntity.builder()
                    .id(item)
                    .purchaseId(finalPurchaseId)
                    .status(PurchaseDetailStatusEnum.ASSIGNED.getCode())
                    .build();
        }).collect(Collectors.toList());
        // 批量修改
        detailService.updateBatchById(detailEntities);

        PurchaseEntity purchaseEntity = PurchaseEntity.builder()
                .id(purchaseId)
                .updateTime(new Date())
                .build();
        this.updateById(purchaseEntity);
    }

    @Override
    public void received(List<Long> ids) {
        // 确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> purchaseEntities = ids.stream()
                .map(id -> this.getById(id))
                .filter(item -> {
                    if (item.getStatus() == PurchaseStatusEnum.CREATED.getCode() ||
                            item.getStatus() == PurchaseStatusEnum.ASSIGNED.getCode()) {
                        return true;
                    }
                    return false;
                }).map(item -> {
                    item.setStatus(PurchaseStatusEnum.RECEIVE.getCode());
                    item.setUpdateTime(new Date());
                    return item;
                }).collect(Collectors.toList());

        // 改变采购单的状态
        this.updateBatchById(purchaseEntities);

        // 改变采购项的状态
        purchaseEntities.forEach(item -> {
            List<PurchaseDetailEntity> entities = detailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> detailEntities = entities.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetailEntity = PurchaseDetailEntity.builder()
                        .id(entity.getId())
                        .status(PurchaseDetailStatusEnum.BUYING.getCode())
                        .build();
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            detailService.updateBatchById(detailEntities);
        });
    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        // 改变采购项状态
        Long id = purchaseDoneVo.getId();
        Boolean flag = true;
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = PurchaseDetailEntity.builder().build();
            if (item.getStatus() == PurchaseDetailStatusEnum.BUYFAIL.getCode()) {
                flag = false;
                detailEntity.setStatus(PurchaseDetailStatusEnum.BUYFAIL.getCode());
            } else {
                detailEntity.setStatus(PurchaseDetailStatusEnum.FINISH.getCode());
                // 将成功采购的进行入库
                PurchaseDetailEntity entity = detailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        detailService.updateBatchById(updates);

        // 改变采购单状态
        PurchaseEntity purchaseEntity = PurchaseEntity.builder()
                .id(id)
                .status(flag ? PurchaseStatusEnum.FINISH.getCode() : PurchaseStatusEnum.HASERROR.getCode())
                .updateTime(new Date())
                .build();
        this.updateById(purchaseEntity);
    }

}